//
//  KqPhotoAlert.m
//  kq_flutter_widgets
//
//  Created by wtb on 2023/4/12.
//

#import "KqPhotoAlert.h"
#import "KqTool.h"
#import "WMZDialog.h"
#import "KqScreenUtil.h"
#import "KqUIAssetsManager.h"
#import "TZImagePickerController.h"

static KqPhotoAlert *instance = nil;

@implementation KqPhotoAlert

+ (KqPhotoAlert *)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        instance = [[super allocWithZone:NULL] init];
    });
    return instance;
}

+ (id)allocWithZone:(struct _NSZone *)zone {
    return [self sharedInstance];
}

-(void)handleSelectLibraryWithTarget:(id)target maxCount:(int)count{
    [self handleSelectWithTarget:target maxCount:count isCamera:NO];
}

-(void)handleSelectCameraWithTarget:(id)target{
    [self handleSelectWithTarget:target maxCount:1 isCamera:YES];
}

-(void)handleSelectWithTarget:(id)target maxCount:(int)count isCamera:(BOOL)isCamera{
    __weak __typeof(self)GF = self;
    if (isCamera) {
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
            //没有访问相机的权限
            [GF handleNotAuthorized:isCamera];
        }else{
            [GF handlePickerImgVC:isCamera target:target maxImagesCount:count];
        }

    }else{
        KqUIAssetAuthorizationStatus status = [KqUIAssetsManager authorizationStatus];
        if (status == KqUIAssetAuthorizationStatusAuthorized) {
            //已经授权
            //去选择图片
            NSLog(@"已经授权");
            [self handlePickerImgVC:isCamera target:target maxImagesCount:count];
        }else if(status == KqUIAssetAuthorizationStatusNotDetermined){
            //还不确定有没有授权
            NSLog(@"还不确定有没有授权");
            //由于获取权限的方式是异步的，可能会慢 所以在这里加一个判断
            [KqUIAssetsManager requestAuthorization:^(KqUIAssetAuthorizationStatus status) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (status == KqUIAssetAuthorizationStatusAuthorized) {
                        //已经授权
                        //去选择图片
                        [GF handlePickerImgVC:isCamera target:target maxImagesCount:count];
                    }else if(status == KqUIAssetAuthorizationStatusNotAuthorized){
                        //禁止了授权
                        NSLog(@"禁止了授权");
                        [GF handleNotAuthorized:isCamera];
                    }
                });
            }];
        }else if(status == KqUIAssetAuthorizationStatusNotAuthorized){
            //禁止了授权
            NSLog(@"禁止了授权");
            [GF handleNotAuthorized:isCamera];
        }
    }
}

- (void)handleNotAuthorized:(BOOL)isCamera{
    NSString *msg = isCamera?@"您已禁止应用相机权限，如需使用此功能请到设置中授权权限。":@"您已禁止应用相册权限，如需使用此功能请到设置中授权权限。";
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        Dialog()
            .wTypeSet(DialogTypeNornal)
            .wWidthSet(ScreenWidth()-72)
            .wTitleSet(@"权限申请")
            .wMessageSet(msg)
            .wOKTitleSet(@"确定")
            .wOKColorSet([UIColor redColor])
            .wCancelTitleSet(@"取消")
            .wShadowCanTapSet(NO)
            .wCancelColorSet([UIColor blueColor])
            .wEventOKFinishSet(^(id anyID, id otherData) {
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
                }
            })
            .wStart();
//        GFAlertButton *confirm = [GFAlertButton initWithTitle:Localized(@"ok", @"Home") titleColor:GFColor(@"#40a9ff") action:^(NSString *str) {
//            NSLog(@"禁止了授权");
//            [GFAlert removeAlert];
//            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
//            if ([[UIApplication sharedApplication] canOpenURL:url]) {
//                [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
//            }
//         }];
//        GFAlertButton *cancelButton = [GFAlertButton initWithTitle:Localized(@"cancel",@"Home") titleColor:GFColor(@"#999999") action:nil];
//
//        [GFAlert showWithTitle:Localized(@"protolApply", @"Public") content:isCamera ? Localized(@"protolCamerDetail", @"Public") : Localized(@"protolDetail", @"Public") confirmButton:confirm cancelButton:cancelButton];
    }];
}

- (void)handlePickerImgVC:(BOOL)isCamera target:(id)target maxImagesCount:(int)count
{
    __weak __typeof(self)GF = self;
    if (isCamera) {
        //相机 拍照
        UIImagePickerController *pickerVC = [[UIImagePickerController alloc] init];
        pickerVC.modalPresentationStyle = UIModalPresentationCurrentContext;
        pickerVC.allowsEditing = NO;
        pickerVC.delegate = target;
        pickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            if ([KqTool getNav]) {
                [[KqTool getNav] presentViewController:pickerVC animated:YES completion:nil];
            }else{
                [[KqTool getRootController] presentViewController:pickerVC animated:YES completion:nil];
            }
        }]
        ;
    }else{
        //相册
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:count columnNumber:4 delegate:target pushPhotoPickerVc:YES];
        imagePickerVc.selectPicText = @"已选择 ## 张照片";
        imagePickerVc.doneBtnTitleStr = @"确定";
        imagePickerVc.oKButtonTitleColorDisabled = [UIColor whiteColor];
        imagePickerVc.oKButtonTitleColorNormal = [UIColor whiteColor];
        imagePickerVc.okButtonBgColor = [UIColor colorWithRed:64/255.0 green:169/255.0 blue:1 alpha:1];
        imagePickerVc.allowPickingOriginalPhoto = NO;
        imagePickerVc.selectPicCountColor = [UIColor whiteColor];
        imagePickerVc.selectPicOtherColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.5];
        imagePickerVc.naviBgColor = [UIColor colorWithRed:58/255.0 green:85/255.0 blue:155/255.0 alpha:1];
        imagePickerVc.showPhotoCannotSelectLayer = YES;
        imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
        imagePickerVc.allowTakeVideo = NO;
        imagePickerVc.allowTakePicture = NO;
        imagePickerVc.allowPickingVideo = NO;
        imagePickerVc.allowPreview = NO;
//        imagePickerVc.navItemRightImg = [UIImage imageNamed:@"ic_guanbi"];
//        imagePickerVc.navItemLeftText = Localized(@"lastObj", @"Public");
//        imagePickerVc.navTitle = Localized(@"loadupPhotoImg", @"Public");
        imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
        imagePickerVc.beyondToast = [@"最多可选##张照片" stringByReplacingOccurrencesOfString:@"##" withString:[NSString stringWithFormat:@"%d",count]];
        imagePickerVc.bottomToolBarColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1];
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            if (target && [target respondsToSelector:@selector(photoAlert:images:)]) {
                [target photoAlert:GF images:photos];
            }
        }];

        imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            if ([KqTool getNav]) {
                [[KqTool getNav] presentViewController:imagePickerVc animated:YES completion:nil];
            }else{
                [[KqTool getRootController] presentViewController:imagePickerVc animated:YES completion:nil];
            }
        }];
    }
}

@end
